<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <!-- 搜索区域 -->
        <!-- 搜索按钮绑定点击事件 -->
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 添加按钮 -->
        <el-col :span="3">
          <el-button type="primary" @click="addUserDialog = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userlist.users" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽知识点 -->
          <template slot-scope="scope">
            <!-- 用户状态按钮 -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="210px">
          <template v-slot="scop">
            <!-- 修改按钮  -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="edit(scop.row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="del(scop.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->

            <el-tooltip effect="dark" content="分配角色" placement="top">
              <el-button
                type="warning"
                icon="el-icon-user-solid"
                @click="setRol(scop.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 底部分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <!-- 添加关闭用户对话框 close事件,实现关闭对话框之后清空表单的内容 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserDialog"
      width="50%"
      @close="addUserClear"
    >
      <!-- 对话框主体内容表单区域 -->
      <el-form
        :model="addUserForm"
        :rules="addUserRules"
        ref="addUserRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile" type="number">
          <el-input v-model.number="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <!-- 对话框底部按钮区域 -->
        <el-button @click="addUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="dilogclose"
    >
      <el-form
        :model="addUserForm"
        :rules="editUser"
        ref="addUserRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile" type="number">
          <el-input v-model.number="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editsubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色弹出框 -->
    <el-dialog title="角色分配" width="50%" :visible.sync="roleVisible">
      <el-select v-model="rolId" placeholder="请选择角色">
        <el-option
          v-for="item in rolList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <span slot="footer">
        <el-button @click="roleVisible = false">取消</el-button>
        <el-button type="primary" @click="setRolOk">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'user',
  data () {
    return {
      // 分配角色对话框
      roleVisible: false,
      //  编辑对话框
      editdialogVisible: false,
      //  1.2 用户列表参数对象
      queryInfo: {
        query: '',
        //  当前显示页绑定
        pagenum: 1,
        //  当前每页显示多少数据
        pagesize: 10
      },
      userlist: '',
      total: 0,
      //    添加用户对话框控制
      addUserDialog: false,
      //  添加用户表单绑定数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //  用户角色列表
      rolList: [],
      // 选择的角色id
      rolId: '',
      id: '',
      //  添加用户表单验证规则
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value.toString().length != 11) {
                return callback(new Error('手机号错误!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      editUser: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value.toString().length != 11) {
                return callback(new Error('手机号错误!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    //  确定分配

    async setRolOk () {
      const { data: res } = await this.$http.put(`users/${this.id}/role`, {
        rid: this.rolId
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('分配成功!')
      this.roleVisible = false
      this.rolId = ''
    },
    //  分配角色
    async setRol (id) {
      this.roleVisible = true
      this.id = id
    },
    //  1.1请求用户列表函数
    async getUserList () {
      const { data: res } = await this.$http.get('/users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error(this.meta.msg)
      this.userlist = res.data
      this.total = res.data.total
    },
    //  分页器--切换每一页显示条数时触发
    handleSizeChange (newPage) {
      //  修改请求参数
      this.queryInfo.pagesize = newPage
      // 重新发送请求
      this.getUserList()
    },
    //  分页器--监听页码值改变的事件
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      // 重新发送请求
      this.getUserList()
    },
    //  用户状态按钮 switch开关改变事件
    async userStateChange (newstate) {
      //  状态改变调用接口(1.33)请求改变
      const { data: res } = await this.$http.put(
        `users/${newstate.id}/state/${newstate.mg_state}`
      )
      if (res.meta.status !== 200) {
        newstate.mg_state = !newstate.mg_state
        return this.$message.error('用户状态更新失败!')
      }
      this.$message.success('用户状态更新成功!')
    },
    //  关闭添加用户框清空表单内容事件
    addUserClear () {
      this.$refs.addUserRef.resetFields()
    },
    //  添加用户对话框底部按钮事件
    addUser () {
      //  表单预校验
      this.$refs.addUserRef.validate(async valid => {
        if (!valid) return
        //  预校验成功 发送添加用户请求
        const { data: res } = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败!')
        }
        this.$message.success('添加用户成功!')
        //  添加用户成功关闭添加用户状态框
        this.addUserDialog = false
        //  重新请求用户列表渲染
        this.getUserList()
      })
    },
    //  修改按钮点击事件
    edit (data) {
      this.editdialogVisible = true
      this.addUserForm.username = data.username
      this.addUserForm.email = data.email
      this.addUserForm.mobile = data.mobile
      this.addUserForm.id = data.id
    },
    //  修改框提交提交按钮点击事件
    async editsubmit () {
      this.$refs.addUserRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `users/${this.addUserForm.id}`,
          this.addUserForm
        )
        if (res.meta.status === 200) {
          this.getUserList()
          this.$message.success('修改成功~')
          this.editdialogVisible = false
        } else {
          this.$message.error(res.meta.msg)
        }
      })
    },
    //  编辑用户对话框关闭回调
    dilogclose () {
      this.addUserForm = {
        username: '',
        password: '',
        email: '',
        mobile: ''
      }
    },
    //  删除按钮点击事件
    del (id) {
      // 删除对话框
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${id}`)
          if (res.meta.status === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.queryInfo.pagenum = 1
            this.getUserList()
          } else {
            this.$message({
              type: 'error',
              message: res.meta.msg
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  },
  async created () {
    //  1.页面一加载就请求用户列表
    this.getUserList()
    //  2.获取角色列表
    const { data: res } = await this.$http.get('roles')
    res.data.forEach(item => {
      this.rolList.push({
        id: item.id,
        roleName: item.roleName
      })
    })
  }
}
</script>
<style lang="less" scoped>
.el-table {
  font-size: 12px;
  margin-top: 15px;
}
.el-pagination {
  margin-top: 30px;
}
</style>
